package com.ftg.learn.chapter04.service;

import com.ftg.learn.chapter04.dao.BedRoomDao;
import com.ftg.learn.chapter04.domain.BedRoom;
import com.ftg.learn.chapter04.domain.Human;

/**
 * 业务逻辑
 *
 * @author 布衣
 */
public class BedRoomService {

    private BedRoomDao bd = new BedRoomDao();

    /**
     * 获取所有寝室列表
     */
    public BedRoom[] getAllBedRoom() {
        return bd.getAllRooms();
    }

    public boolean saveBedRoom(String doorNum, String address, int humNum, int firmNum) {
        return bd.saveBedRoom(doorNum, address, humNum, firmNum);
    }

    /**
     * 分配寝室
     */
    public boolean shareBedRoom(String doorNum, String address, Human... hs) {
        if (hs.length == 0) {
            return false;
        }

        int len = hs.length % 4 == 0 ? hs.length / 4 : hs.length / 4 + 1;

        for (int i = 0; i < hs.length; i += 4) {
            BedRoom b1 = bd.createBedRoom(4, 8);
            b1.setDoorNum(doorNum);
            b1.setAddress(address);
            System.out.println(b1);
            for (int i1 = 0; i1 < 4; i1++) {
                if (i + i1 < hs.length) {
                    b1.intoBedRoom(hs[i + i1]);
                }
            }
        }

        bd.setRestNum(bd.getRestNum() - hs.length);
        return true;
    }

    public void autoSharBedRoom(Human... hs) {
        //性能问题
        if (bd.getRestNum() < hs.length) {
//            throw new RuntimeException("寝室数量不足,请老大爷进行寝室维护!!!");
            System.out.println("寝室数量不足,请老大爷进行寝室维护!!!");
            return ;
        }
        //表示hs开始分配的位置
        int begin = 0;
        BedRoom[] allRooms = bd.getAllRooms();
        for (BedRoom one : allRooms) {
            if (begin == hs.length) {
                break;
            }
            int x = one.getHumanNum() - one.getHumanSize();
            if (x > 0) {
                for (int i = 0; i < x && begin < hs.length; i++) {
                    one.intoBedRoom(hs[begin++]);
                }
            }
        }

    }
}
